package org.annoflow.filter.boundry;

import org.annoflow.audit.ContextTracker;
import org.annoflow.filter.FilterPoint;
import org.annoflow.policy.PolicyType;
import org.annoflow.policy.PolicyManager;
import org.annoflow.policy.boundry.InsecureClassPolicy;
import org.annoflow.policy.boundry.SecureClassPolicy;

public class MixFilter implements FilterPoint{

	@Override
	public String getFilterCode() {
		return "org.annoflow.filter.boundry.MixFilter.mixParams(this);";
	}
	public static void mixParams(Object self)
	{
		PolicyType selfPolicy = PolicyManager.lookupObjectPolicy(self);
		if(selfPolicy instanceof SecureClassPolicy)
		{
				if(!isCallerSecure())
				{
					PolicyManager.setObjectPolicy(self, new InsecureClassPolicy());
				}
		}
	}
	//TODO: Refactor
	private static boolean isCallerSecure()
	{
//		StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
//		StackTraceElement element = stackTrace[4];
		String caller = ContextTracker.getInstance().getCallerContext();
		try {
			Class<?> parentCaller = Class.forName(caller);
			PolicyType policy = PolicyManager.lookupClassPolicy(parentCaller);
			if (policy != null) {
				if (!policy.getClass().equals(SecureClassPolicy.class)) {
					return false;
				}
			}
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		return true;
	}
	@Override
	public String getReturnFilterCode() {
		// TODO Auto-generated method stub
		return null;
	}

}
